/**
 * Created by 居胜 on 2016/6/1.
 */
var DIALOG = (function () {
    "use strict";

    //闭包，不暴露addClass, removeClass两个函数
    function addClass(obj, cls) {
        var obj_class = obj.className; //获取class内容
        var blank = (obj_class == "") ? "" : " ";
        var added = obj_class + blank + cls;
        obj.className = added; //替换class
    }

    function removeClass(obj, cls){
        var obj_class = " " + obj.className + " "; //首尾加空格
        obj_class = obj_class.replace(/(\s+)/gi, " "); //替换多余空格
        var removed = obj_class.replace(" " + cls + " ", " ");
        removed.replace(/(^\s+)|(\s+$)/g, "");
        obj.className = removed;
    }

    //初始化函数
    function GetDialog(width, height) {
        var width = width || "350px";
        var height = height || "150px";

        this.dialog = document.createElement("div");
        this.title = document.createElement("h3");
        this.content = document.createElement("p");
        this.buttons = document.createElement("div");
        
        addClass(this.dialog, "overlay");
        addClass(this.buttons, "buttons");
        document.body.appendChild(this.dialog);
        this.dialog.appendChild(this.buttons);

        var self = this;
        document.body.onclick = function (event) {
            if(event.target.className.toUpperCase() == "CANCEL") {
                GetDialog.prototype.hidden(self);
            }
        }
    }

    //加入标题
    GetDialog.prototype.addTitle = function (tit) {
        this.title.innerHTML = tit;
        addClass(this.title, "title");
        this.dialog.appendChild(this.title);
    };

    //加入内容
    GetDialog.prototype.addContent = function (cont) {
        this.content.innerHTML = cont;
        addClass(this.content, "content");
        this.dialog.appendChild(this.content);
        console.log(this.dialog)
    };

    //加入OK按钮
    GetDialog.prototype.addOKButton = function (text) {
        this.okButton = document.createElement("div");
        this.okButton.innerHTML = text;
        addClass(this.okButton, "ok");
        this.buttons.appendChild(this.okButton);
    };
    
    //cancel按钮
    GetDialog.prototype.addCancelButton = function (text) {
        this.cancelButton = document.createElement("div");
        this.cancelButton.innerHTML = text;
        addClass(this.cancelButton, "cancel");
        this.buttons.appendChild(this.cancelButton);
    };

    GetDialog.prototype.hidden = function (self) {
        document.body.removeChild(self.dialog);
    };
    
    return GetDialog;
})();

function init(){
    var dialog = new DIALOG();
    dialog.addTitle("这是一个浮出层");
    dialog.addContent("点击取消关闭浮出层");
    dialog.addOKButton("ok");
    dialog.addCancelButton("cancel");
}